package kr.or.javacafe.app01.controller;

import java.util.List;
import java.util.Locale;

import kr.or.javacafe.app01.domain.CodeMaster;
import kr.or.javacafe.app01.domain.CodeSlave;
import kr.or.javacafe.app01.service.CodeMasterService;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping("/app/01")
public class App01Controller {
	
	private static final Logger logger = LoggerFactory.getLogger(App01Controller.class);
		
	@Autowired
	private CodeMasterService codeMasterService;
	
	
	@RequestMapping(value = "/main", method = RequestMethod.GET)
	public String main(Locale locale, Model model) {
		
		List<CodeMaster> codeMasterList = codeMasterService.findCodeMasterList();
		model.addAttribute("codeMasterList", codeMasterList);
		
		return "app01/main";
	}
	
	@RequestMapping(value = "/mcode/{mcode}", method = RequestMethod.GET)
	public String slaveCode(@PathVariable String mcode, Locale locale, Model model) {
		
		List<CodeSlave> codeSlaveList = codeMasterService.findCodeSlaveList(mcode);
		model.addAttribute("codeSlaveList", codeSlaveList);
		model.addAttribute("mcode", mcode);
		
		return "app01/slaveCode";
	}

	
	
	@RequestMapping(value = "/ajax/mcode/{mcode}", produces = "application/json")
	@ResponseBody
	public ResponseEntity<String> ajaxMCode(@PathVariable String mcode) {
		
		List<CodeSlave> codeSlaveList = codeMasterService.findCodeSlaveList(mcode);

		String strJSON = "";
		try {			
			ObjectMapper om = new ObjectMapper();
			strJSON = om.defaultPrettyPrintingWriter().writeValueAsString(codeSlaveList);

		} catch (Exception ex) {
			logger.info(ex.getMessage());
			strJSON = "{\"result\" : \"error\"}";
		}
		
		HttpHeaders header = new HttpHeaders();
		header.add("Content-Type", "application/json; charset=UTF-8");

		return new ResponseEntity<String>(strJSON, header, HttpStatus.OK);
	}
	
	
	
	
	
	
	
}
